﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json.Linq;
using Samurai.Infrastructure;

namespace Samurai.MovieIndustry
{
    public class ImdbApiMovieService : IMovieService
    {
        public Movie GetInfo(string query)
        {
            

            var req = WebRequest.Create(string.Format("http://www.imdbapi.com/?i=&t={0}", query));

            var response = req.GetResponse();

            var responseStream = response.GetResponseStream();
            var reader = new StreamReader(responseStream);
            var data = reader.ReadToEnd();

            var o = JObject.Parse(data);

            var title = (string)o.SelectToken("Title");
            var genres = (string)o.SelectToken("Genre");
            var rating = (string)o.SelectToken("Rating");
            var year = (string)o.SelectToken("Year");

            var error = (string)o.SelectToken("Response");

            if (error == "Parse Error")
                error = Constants.ErrorFilmNotFound;
            else if (error == "True")
                error = string.Empty;

            var imdbID = (string)o.SelectToken("ID");
            var url = string.Format("http://www.imdb.com/title/{0}", imdbID);

            var imageUrl = (string)o.SelectToken("Poster");

            var info = new Movie
            {
                Title = title,
                Rating = rating,
                Year = year,
                Error = error,
                Genres = BuildGenreTitles(genres),
                Url = url,
                ImageUrl = imageUrl
            };


            return info;
        }

        private static string[] BuildGenreTitles(string genres)
        {
            if (genres == null)
                return new string[] { };

            return genres.Split(',').Select(s => s.Trim(' ')).ToArray();
        }
    }
}
